package org.rqb.panel;

import com.github.kwhat.jnativehook.GlobalScreen;
import lombok.extern.slf4j.Slf4j;
import org.rqb.config.MyConfig;
import org.rqb.entry.MyEvent;
import org.rqb.frame.MyFrame;
import org.rqb.listener.RepeatMouseAndKeyRepeatListener;
import org.rqb.robot.MyRobot;
import org.rqb.ui.button.MyTextureButton;
import org.rqb.ui.panel.BackgroundPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import static org.rqb.Constant.EXECUTED_TIMES_STR;
import static org.rqb.Constant.REPEAT_NUM;

@Slf4j
public class RepeatPanel extends BackgroundPanel implements ActionListener {

    private JPanel cardPanel;
    private CardLayout cardLayout;
    private MyFrame myFrame;
    private Properties myConfig = MyConfig.getConfig();
    private MyTextureButton startButton;
    private MyTextureButton repeatButton;
    private JTextField inputField;
    private RepeatMouseAndKeyRepeatListener repeatMouseAndKeyRepeatListener = new RepeatMouseAndKeyRepeatListener(this);
    private MyRobot myRobot;;
    private Thread repeatThread;
    private JLabel tips1;
    private JLabel tips2;
    private JLabel executedTimes;
    private JLabel tips3;

    public RepeatPanel(JPanel cardPanel, CardLayout cardLayout, MyFrame myFrame) {
        super("/images/repeatBg.png");
        this.cardPanel = cardPanel;
        this.cardLayout = cardLayout;
        this.myFrame = myFrame;

        myRobot = MyRobot.getInstance().init(myFrame,this);
        initComponents();
        setLayout(new GridBagLayout()); // 使用GridBagLayout进行布局
        layoutComponents(); // 布局组件
    }

    private void initComponents() {
        // 初始化按钮
        startButton = new MyTextureButton("录制开始");
        repeatButton = new MyTextureButton("复现");

        executedTimes = new JLabel(String.format(EXECUTED_TIMES_STR,0));
        tips1 = new JLabel("ctrl + E （end）  停止录制");
        tips2 = new JLabel("ctrl + Q （quit） 停止复现 （执行完该次操作才停止）");
        tips3 = new JLabel("ctrl + S （stop） 立即停止复现");

        tips1.setSize(100,200);

        // 初始化文本框，并添加只能输入整数的限制
        inputField = new JTextField(10); // 设置文本框的列数
        inputField.setText(myConfig.getProperty(REPEAT_NUM));
        inputField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                // 只允许输入数字
                if (!Character.isDigit(c)) {
                    e.consume();
                }
            }
        });

        // 添加按钮点击事件监听
        startButton.addActionListener(this);

        repeatButton.addActionListener(this);

    }


    private void layoutComponents() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // 设置组件之间的间距

        // 布局录制开始按钮
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(startButton, gbc);

        // 布局复现按钮
        gbc.gridx = 1;
        gbc.gridy = 0;
        add(repeatButton, gbc);

        // 布局文本框
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2; // 使文本框跨越两列
        add(inputField, gbc);

        //添加已经执行次数
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        add(executedTimes, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        add(tips1, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        add(tips2, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        add(tips3, gbc);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof MyTextureButton) {
            MyTextureButton btn = (MyTextureButton) e.getSource();
            switch (btn.getText()) {

                case "录制开始" :
                    log.info("录制开始按钮被点击");
                    listenMouse();
                    break;

                case "录制结束" :
                    log.info("录制结束按钮被点击");
                    stopRecordListener();
                    break;

                case "复现" :
                    log.info("复现按钮被点击");
                    repeatByRobot();
                    break;


            }


        }
    }

    private void repeatByRobot() {
        //获取用户输入
        int count;
        try {
            count = Integer.parseInt(inputField.getText());
            //保存用户数字到配置文件
            updateConfig(count);
        } catch (NumberFormatException e) {
            log.error("整数数字输入异常");
            throw new RuntimeException(e);
        }

        myFrame.setState(JFrame.ICONIFIED);
        //获取事件列表
        List<MyEvent> eventList = repeatMouseAndKeyRepeatListener.getEventList();
        if (eventList != null && !eventList.isEmpty()) {
            repeatThread = new Thread(() -> {
                try {
                    myRobot.setLoop(false);
                    myRobot.executeEvents(eventList, count);
                } catch (InterruptedException e) {
                    log.info("中断复现线程");
                }
            });
            repeatThread.start();
        } else {
            log.info("还没有记录");
        }


    }

    private void updateConfig(int count) {
        HashMap<String, String> param = new HashMap<>();
        param.put(REPEAT_NUM, String.valueOf(count));

        MyConfig.updateConfig(param);
    }

    private void listenMouse () {
        // 清空事件列表
        repeatMouseAndKeyRepeatListener.clearEvent(System.currentTimeMillis());

        GlobalScreen.addNativeMouseListener(repeatMouseAndKeyRepeatListener);
        GlobalScreen.addNativeMouseMotionListener(repeatMouseAndKeyRepeatListener);
        GlobalScreen.addNativeMouseWheelListener(repeatMouseAndKeyRepeatListener);
        //监听键盘事件
        GlobalScreen.addNativeKeyListener(repeatMouseAndKeyRepeatListener);

        startButton.setText("录制结束");
        repeatButton.setEnabled(false);//设置复现按钮不可被点击
        //设置MyFrame最小化
        myFrame.setState(JFrame.ICONIFIED);

        log.info("全局鼠标监听启动");
    }

    public void stopRecordListener() {
        // 移除鼠标监听器
        GlobalScreen.removeNativeMouseListener(repeatMouseAndKeyRepeatListener);
        GlobalScreen.removeNativeMouseMotionListener(repeatMouseAndKeyRepeatListener);
        GlobalScreen.removeNativeMouseWheelListener(repeatMouseAndKeyRepeatListener);
        //一处键盘监听
        GlobalScreen.removeNativeKeyListener(repeatMouseAndKeyRepeatListener);
        startButton.setText("录制开始");
        repeatButton.setEnabled(true); //复现按钮可以被点击
        log.info("复现键盘鼠标监听器关闭");
    }

    /**
     * 离开复现，会执行完当前次
     */
    public void quitRepeat(){
        myRobot.setLoop(true);
    }

    /**
     * 立刻结束
     */
    public void stopRepeat(){
        if (repeatThread != null && repeatThread.isAlive()) {
            repeatThread.interrupt();
            myRobot.repeatClosed();
        }
        if (repeatThread != null && repeatThread.isAlive()){
            repeatThread.stop();
        }
    }


    public void updateExecutedTimes(int times){
        SwingUtilities.invokeLater(()->{
            executedTimes.setText(String.format(EXECUTED_TIMES_STR,times));

        });


    }



}
